/** @license torrent.js
 * Copyright (c) 2009 Fedor Indutny
 * License: GNU General Public License version 3 or later
 */
$(function () {
  var documentlocationhref=document.location.href;
  var sk=false,ck=false,ak=false,mouse=false;
  var overlay=document.createElement('div');
  overlay.setAttribute('id','--tcd-overlay');
  var tcdddd=$(overlay);


  var st='text-align:center;background-color:#000000;color:#FFFFFF;opacity:0.8;position: absolute;left: 0px;right: 0px;display: none;-webkit-box-shadow: black 0px 0px 5px;border-bottom-left-radius: 7px 7px;border-bottom-right-radius: 7px 7px;border-top-left-radius: 7px 7px;border-top-right-radius: 7px 7px;width:250px;height:auto;font-size:10px;padding:15px;z-index:999';
  overlay.setAttribute('style',st);
  document.body.appendChild(overlay);
  // Hook any mouse hover over a
  // For memory leaks paranoid
  //Get user trackers
  chrome.extension.onRequest.addListener(Response);
  chrome.extension.connect().postMessage('#^%connect');
  var timer;
  function uResponse(uText) {
    if (uText[0]=='---') {   
            overlay.innerHTML=uText[1];
            
    }
    chrome.extension.onRequest.removeListener(uResponse);
  };
  function Response(uTrackers) {
      var allaas=$("a");
      allaas.hover(function(e) {
      if ((e.ctrlKey==ck)&&(e.altKey==ak)&&(e.shiftKey==sk)) {
        if (mouse==1) {
          var ethref;
          aaa=e.target;
          while ((aaa.parentNode)&&(aaa.nodeName!='A'))
          aaa=aaa.parentNode;
          ethref=aaa.href;
          chrome.extension.onRequest.addListener(uResponse);
          var x=e.clientX;
          var y=e.clientY;
    
          if (timer) clearTimeout(timer);
   
          timer=setTimeout(function () {
            chrome.extension.connect().postMessage(new Array('^^^',ethref));
            var tx=document.body.scrollLeft+x;
            if (tx+280>document.body.clientWidth) tx-=(tx+280-document.body.clientWidth);
            overlay.style.left=tx+'px';
 
            overlay.style.top=document.body.scrollTop+y+'px';
            overlay.innerHTML='<u>Loading...</u>';
            tcdddd.fadeIn(500);
          },800);
        }
      }
      
      if (tcdddd.display!='none')
        tcdddd.fadeOut('fast');
    }); 

    chrome.extension.onRequest.removeListener(Response);
  

    var trackers= [];
    var foundtracker=false;
    // * Trackers array 
    // * You can add your own tracker using this example:
    // * trackers.push({main:/^http:\/\/site\.com\/.*/, download:""});
    // * main - regex of site, download:a.href value of links on this tracker
    // * title: r - regex of replace function that must remain id of topic
    // * title: url - link to topic
    trackers.push({main:/^http:\/\/(www\.)?what\.cd\/.*/mgi, download:/torrents\.php\?action=download\&id=[0-9]+/i},
    {main:/^http:\/\/(www\.)?torrents\.ru\/.*/mgi, download:/http:\/\/dl\.torrents\.ru\/forum\/dl\.php\?t=/i},
    {main:/^http:\/\/(www\.)?torrents\.net\.ua\/forum\/.*/mgi, download:/download\.php\?id=/i},
    {main:/^http:\/\/(www\.)?free-torrents\.org\/forum\/.*/mgi, download:/download\.php\?id=/i},
    {main:/^http:\/\/(www\.)?thepiratebay\.org\/.*/mgi, download:/\.torrent$/i},
    {main:/^http:\/\/(www\.)?isohunt\.com\/.*/mgi, download:/\.torrent$/i},
    {main:/^http:\/\/(www\.)?kinozal\.tv\/.*/mgi, download:/\.torrent$/i},
    {main:/^http:\/\/(www\.)?mininova\.org\/tor\/[0-9]*.*/mgi, download:/\/get\/[0-9]+/i},
    {main:/^https:\/\/(www\.)?waffles\.fm\/.*/mgi, download:/download\.php\/[0-9]+\/[0-9]+\//i},
    {main:/^http:\/\/(www\.)?lostfilm\.tv\/.*/mgi, download:/\.torrent$/i},
    {main:/^http:\/\/(www\.)?nnm-club\.ru\/forum\/.*/mgi, download:/download\.php\?id=[0-9]+/i},
    {main:/^http:\/\/(www\.)?pirat\.ca\/.*/mgi, download:/download\.php\?id=[0-9]+/i},
    {main:/^http:\/\/(www\.)?kickasstorrents\.com\/.*/mgi, download:/http:\/\/torrage\.com\/torrent\//i},
    {main:/^http:\/\/(www\.)?btjunkie\.org\/.*/mgi, download:/http:\/\/dl\.btjunkie\.org\/torrent\//i},
    {main:/^http:\/\/(www\.)?torrents.by\/.*/mgi, download:/dl[0-9]+$/gim},
    {main:/^http:\/\/eztv\.it\/.*/mgi, download:/\.torrent$/mgi});
    ck=(uTrackers[0].ck);
    sk=uTrackers[0].sk;
    ak=uTrackers[0].ak;
    mouse=uTrackers[0].mouse;
    for (i=1;uTrackers[i];i++) 
      trackers.push({main:new RegExp(uTrackers[i].main,'mgi'), download:new RegExp(uTrackers[i].download,'mgi')});    
    // Find what site is opened now
    for (i in trackers) {
      var tti=trackers[i];
      if (tti.main.test(documentlocationhref)) {
       // Add icon if see there any torrent link 
  /*        var result = document.evaluate(
            s1+trackers[i].download+s2,
            document, null, 0, null);
  */
        var item;
        var ttid=tti.download;
        if (item = allaas.filter(function (){return ttid.test(this.href);})) {
          if (item.length) {
            foundtracker=true;
            chrome.extension.connect().postMessage([item[0].href]);
          }
        }

        break;
      }
    }
    if (!foundtracker) {
    // Kickass support
    if ((/^http:\/\/www\.kickasstorrents\.com\/.*/gim).test(documentlocationhref)) {
       // Add icon if see there any torrent link 
        var result = document.evaluate(
            '//a[(@class="iverif") or (@class="idirect")]',
            document, null, 0, null);
  
        var item;
        if (item = result.iterateNext())  {
           chrome.extension.connect().postMessage(['$^$kickass',item.href,(documentlocationhref).replace(/\/[^\/]*$/gim,"")+'/']); 
        }
        // Memory Leaks???
        result=null;
        item=null;
        
    }
    //Mininova.org support
    if ((/^http:\/\/www\.mininova\.org\/.*/gim).test(documentlocationhref)) {
       // Add icon if see there any torrent link 
  
        var item;
        if (item = $('a').filter(function (){return (/\/tor\/[0-9]+/i).test(this.href);})) {
          if (item[0]) {
            chrome.extension.connect().postMessage(['$^$mininova',item[0].href,(documentlocationhref).replace(/\/[^\/]*$/gim,"")+'/']); 
          }
        }
        // Memory Leaks???
        result=null;
        item=null;
        
    }
    // Kinozal.tv support
    if ((/^http:\/\/kinozal\.tv\/.*/gim).test(documentlocationhref)) {
       // Add icon if see there any torrent link 
        var result = document.evaluate(
            '//a[contains(@href,"/details.php?id=")]',
            document, null, 0, null);
        var item;
        if (item = result.iterateNext())  {
           chrome.extension.connect().postMessage(['$^$kinozal',item.href,(documentlocationhref).replace(/\/[^\/]*$/gim,"")+'/']); 
        }
        // Memory Leaks???
        result=null;
        item=null;
        
    }
    // Other by mime/type
        var othertest=(/\.torrent(\?[^\.\/]*)?$/gi);
        var othertest2=(/download\.php(\?[^\.\/]*)?$/gi);
        item = allaas.filter(function (){             
          return othertest.test(this.href)||othertest2.test(this.href);
        });
        var jj=0;
        if ((item)&&(item.length))
        for (x in item) {
          jj++;
          if (jj>7) break;
          if (item[x].href)
            chrome.extension.connect().postMessage(['$^$other',item[x].href,(documentlocationhref).replace(/\/[^\/]*$/gim,"")+'/']); 
        }
        // Memory Leaks???
        result=null;
        item=null;
        
    }

    // Memory Leaks???
  }
});
  //Execute only when page loads
/*  var t="load";
  window.addEventListener(t,findTorrents);
  //Memory l....
  t=null;*/